package com.csmp.service.impl;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.Expectation;
import org.hibernate.transaction.ResinTransactionManagerLookup;

import com.bs.bean.RoleLog;
import com.csmp.service.AbstractRoleLogService;

public class RoleLogServiceImpl extends AbstractRoleLogService {

	public int getCount(RoleLog obj) {
		DetachedCriteria criteria=getCriteria(obj);
		criteria.setProjection(Projections.rowCount());
		List<Integer> list=getHibernateTemplate().findByCriteria(criteria);
		if(list == null || list.isEmpty()){
			return 0;
		}
		return list.get(0);
	}

	protected void saveObj(RoleLog entity) {
     getHibernateTemplate().save(entity);
	}

	protected RoleLog loadObj(Serializable id) {
		return (RoleLog) getHibernateTemplate().load(CLASS_NAME, id);
	}

	protected List<RoleLog> searchList(RoleLog obj, int first, int max) {
		DetachedCriteria criteria=getCriteria(obj);
		List<RoleLog> list=getHibernateTemplate().findByCriteria(criteria, first, max);
		return list;
	}
	private DetachedCriteria getCriteria(RoleLog entity){
		DetachedCriteria criteria=DetachedCriteria.forClass(CLASS_NAME).addOrder(Order.desc("operatorTime"));
		if(StringUtils.isNotBlank(entity.getOperator())){
			criteria.add(Restrictions.like("operator", entity.getOperator().trim(), MatchMode.ANYWHERE));
		}
		if(StringUtils.isNotBlank(entity.getOperator2())){
			criteria.add(Restrictions.like("operator2", entity.getOperator2().trim(), MatchMode.ANYWHERE));
		}
		try{
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(StringUtils.isNotBlank(entity.getApprovlDate1()) && StringUtils.isNotBlank(entity.getApprovlDate2())){
				criteria.add(Restrictions.between("operatorTime", sdf.parse(entity.getApprovlDate1()),sdf.parse(entity.getApprovlDate2())));
			}else if(StringUtils.isNotBlank(entity.getApprovlDate1())){
				criteria.add(Restrictions.ge("operatorTime",sdf.parse(entity.getApprovlDate1())));
			}else if(StringUtils.isNotBlank(entity.getApprovlDate2())){
				criteria.add(Restrictions.lt("operatorTime", sdf.parse(entity.getApprovlDate2())));
			}
		}catch (Exception e) {
			e.printStackTrace();
		}	
		return criteria;
	}

}
